package com.fanfanwang.ffw.app.net;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;

import com.fanfanwang.ffw.app.common.LogUtil;
/**
 * 访问Web Service的工具类
 * @author jCuckoo
 * 
 */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
/**
 * @author Administrator
 *
 */
@SuppressLint("NewApi")
public class WebServiceHelper {
	public static String URL = "http://182.92.173.95:82/api/index.php/?wsdl";
	public static String BaseUrl = "http://182.92.173.95:82/api/";
	public static String url_users = "users.php";
	/**二、	首页接口*/
	public static String url_parkings = "parking.php";


	public static final String apiusernamekey = "apiusername";
	public static final String apiusernamevalue = "huoer";
	public static final String apipasswordkey = "apipassword";
	/**商户登录*/
	public static final String _TENANT_LOGIN = "tenantLogin";
	/**i.	parkisreg商户用户名检测*/
	public static final String _PARKISREG = "parkisreg";
	/**iii.	setparkNewPassword设置商户密码*/
	public static final String _SETPARKNEWPASSWORD = "setparkNewPassword";
	/**i.	getParknumList获取停车位列表*/
	public static final String _GETPARKNUMLIST = "getParknumList";
	/**ii.	addParknumss添加停车位*/
	public static final String _ADDPARKNUM = "addParknum";
	/**iii.	delParknum 删除停车位*/
	public static final String _DELPARKNUM = "delParknum";
	/**iv.	setParknumStatus更改停车位状态*/
	public static final String _SETPARKNUMSTATUS = "setParknumStatus";
	/**i.	getMsgList获取预约消息*/
	public static final String _GETMSGLIST = "getMsgList";

	public static String httpXieYiString="http://www.fenfenriji.com/help/term_mob.html";

	static String NAMESPACE = "http://182.92.173.95:82";
	
	static {
		if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.ICE_CREAM_SANDWICH){
			// 4.0以后需要加入下列两行代码，才可以访问Web Service
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
			.detectDiskReads().detectDiskWrites().detectNetwork()
			.penaltyLog().build());

			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
			.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
			.penaltyLog().penaltyDeath().build());
		}
		//4.0以前版本不需要以上设置
	}

	public static boolean isIOException = true;
	/**
	 * @param url          web service路径
	 * @param nameSpace    web service名称空间
	 * @param methodName   web service方法名称
	 * @param params       web service方法参数
	 */
	public static SoapObject getSoapObject(String url,String methodName, String soapAction, HashMap<String, Object> params) {
		String METHOD_NAME = methodName;
		String SOAP_ACTION = soapAction;
		SoapObject soap = null;
		//如果请求不成功则循环请求
		boolean isSucceed = false;
		int index = 0;
		while(!isSucceed && index <3){
			try {
				//实例化SoapObject对象。
				SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);
				if (params != null && params.size() > 0) {
					for (Entry<String, Object> item : params.entrySet()) {
						//如果有参数的话，设置调用参数
						rpc.addProperty(item.getKey(), item.getValue().toString());
					}
				}
				//设置soap请求信息（参数部分为soap协议版本号 ，与要调用的webservice中版本号一致）
				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
				envelope.bodyOut = rpc;
				envelope.dotNet = false;// true--net; false--java; //这里如果设置为TRUE,那么在服务器端将获取不到参数值(如:将这些数据插入到数据库中的话)
				envelope.setOutputSoapObject(rpc);
//				构建传输对象，并指明WSDL文档URL
				HttpTransportSE ht = new HttpTransportSE(BaseUrl + url);
				ht.debug = true;
				//调用WebService(其中参数为1：命名空间+方法名称，2：Envelope对象)
				String soapAction1=NAMESPACE+METHOD_NAME;
//				ht.call(soapAction1, envelope);
				ht.call(SOAP_ACTION, envelope);
				try {
					soap = (SoapObject) envelope.getResponse();
				} catch (Exception e) {
					LogUtil.e("WebServiceHelper", "getSoapObject",e.getMessage());
					soap = (SoapObject) envelope.bodyIn; // // 获取返回的数据
				}
				isSucceed = true;
			} catch (IOException ex) {
				ex.printStackTrace();
				LogUtil.e("WebServiceHelper", "IOException   ex  >> ", ex.getMessage());
				if(!TextUtils.isEmpty(ex.getMessage()) && ex.getMessage().equals("BufferedInputStream is closed")){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//TODO 这里加1没用，因为上面那里还是把index给初始化赋值了。
					index++;
					getSoapObject(url, methodName, soapAction, params);
					isSucceed = false;
				}else {
					isSucceed = true;
				}
			} catch (Exception ex) {
				ex.printStackTrace();
				ex.getMessage();
			}
			index ++;
			LogUtil.e("WebServiceHelper", "getSoapObject   >> " + soap,"   isSucceed  >> " + isSucceed);
		}
		return soap;
	}
}
